Advertisement
Google Ad Slot: content-top
Commonly Used Ansible Ad-hoc Commands
1. Ping a Host or Group of Hosts
The ping module checks connectivity to the managed nodes.
ansible all -m ping
This will ping all the hosts in the inventory and check if Ansible can connect to them.
2. Gather Facts About a Host
The setup module is used to gather detailed information (facts) about the managed hosts.
ansible all -m setup
This retrieves facts like OS type, memory, disk space, IP address, etc., from all hosts.
3. Install a Package
Using the apt (for Debian/Ubuntu) or yum (for Red Hat/CentOS) module, you can install packages on remote hosts.
For Ubuntu/Debian:
ansible webservers -m apt -a "name=nginx state=present"
For Red Hat/CentOS:
ansible webservers -m yum -a "name=httpd state=present"
This installs the nginx package on all hosts in the webservers group for Ubuntu or the httpd package for CentOS.
4. Restart a Service
You can use the service module to manage services like starting, stopping, or restarting them.
ansible all -m service -a "name=nginx state=restarted"
This restarts the nginx service on all hosts.
5. Execute a Shell Command
The shell or command module can be used to run shell commands on remote hosts.
ansible all -m shell -a "uptime"
This command runs uptime on all hosts, displaying how long each system has been running.
6. Copy a File to Remote Hosts
The copy module can be used to copy files from the control node to the managed nodes.
ansible all -m copy -a "src=/path/to/file dest=/remote/path"
This copies the specified file to the destination path on all managed hosts.
7. Reboot a Host
The reboot module is used to reboot a host.
ansible all -m reboot
This reboots all hosts in the inventory.
8. Add a User
The user module can be used to add users to remote systems.
ansible all -m user -a "name=john state=present"
This creates a user named john on all hosts.
9. Check Disk Space
The shell module can be used to run a command like df -h to check the available disk space on remote hosts.
ansible all -m shell -a "df -h"
This shows the disk space usage on all managed nodes.